﻿namespace ApiTemplate.Common
{
    public class WeChatHelper
    {
        /// <summary>
        /// 微信小程序的appid
        /// </summary>
        const string appId = "wx23*******2af";

        /// <summary>
        /// 微信小程序的秘钥
        /// </summary>
        const string secret = "a0ffeb331*******9fcac5e";

        /// <summary>
        /// 敏感词校验的serviceKey
        /// </summary>
        const string evilToken = "wxee446******b11";

        /// <summary>
        /// 获取用户的OpenId
        /// </summary>
        /// <param name="weChatCode">小程序获取到的临时code</param>
        /// <returns>OpenId</returns>
        public static async Task<string> GetOpenIdAsync(string weChatCode)
        {
            var response = await HttpHelper.GetAsync($"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={weChatCode}&grant_type=authorization_code");
            dynamic result = JsonConvert.DeserializeObject<dynamic>(response.Item1);
            return result.openid;
        }

        /// <summary>
        /// 获取临时通行凭证
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetAccessTokenAsync()
        {
            HttpClient client = new();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string listUrl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={secret}";
            HttpResponseMessage httpResponseMessage = client.GetAsync(listUrl).Result;
            httpResponseMessage.Content.Headers.ContentType.CharSet = "utf-8";
            string jsonStr = await httpResponseMessage.Content.ReadAsStringAsync();
            dynamic tokenDto = JsonConvert.DeserializeObject<dynamic>(jsonStr);
            return tokenDto.access_token;
        }

        /// <summary>
        /// 微信小程序推荐的敏感词校验
        /// </summary>
        /// <param name="txt">要检测的词</param>
        /// <returns>是否包含敏感词</returns>
        public static async Task<bool> EvilTokensValidate(string txt)
        {
            string accessToken = await GetAccessTokenAsync();
            object par = new
            {
                service = "wxee4*********8b11",
                api = "msgSecCheck",
                client_msg_id = Guid.NewGuid().ToString(),
                data = new
                {
                    Action = "TextApproval",
                    Text = txt
                }
            };
            var response = await HttpHelper.PostAsync($"https://api.weixin.qq.com/wxa/servicemarket?access_token={accessToken}", JsonConvert.SerializeObject(par));

            var codeResult = JsonConvert.DeserializeObject<dynamic>(response.Item1);
            EvilKeywordData jsonResult = JsonConvert.DeserializeObject<EvilKeywordData>(codeResult.data.ToString());

            return jsonResult.Response.EvilTokens.Count == 0;
        }
    }

    /// <summary>
    /// 敏感词服务的接收参数
    /// </summary>
    class EvilKeywordData
    {
        public EvilKeywordResponse Response { get; set; }
    }

    /// <summary>
    /// 敏感词服务的接收参数
    /// </summary>
    class EvilKeywordResponse
    {
        public string RequestId { get; set; }

        public List<object> EvilTokens { get; set; }
    }
}
